/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
package org.apache.myfaces.test.webapp.impl;

import org.apache.myfaces.test.webapp.api.ResourceFinder;
import org.apache.myfaces.test.webapp.api.WebappTestConfigurator;

import javax.el.ELResolver;
import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.application.ApplicationWrapper;
import javax.faces.event.ActionListener;
import java.lang.reflect.Field;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Cosmin Martinconi, 06.08.2010
 */
public class WebappTestConfiguratorImpl extends WebappTestConfigurator {

    private static final Logger log = Logger.getLogger(WebappTestConfiguratorImpl.class.getName());

    private static final String ARCHIVE_MANAGER = ArchiveManager.class.getName();                                        
    private static final String ANNOTATION_MANAGER = AnnotationManager.class.getName();
    private static final String PROXY_INTERCEPTOR = ProxyInterceptor.class.getName();
    private static final String TEST_ASSERT_ERRORS = TesttErrorManager.class.getName();

    public static final Class DEFAULT_WEBAPP_TESTER = WebappTesterImpl.class;


    public void configure(Class testClass) {
        configureResources();

        // configure the annotation manager
        AnnotationManager.getCurrentInstance().setTestClass(testClass);
        AnnotationManager.getCurrentInstance().initializeAnnotations();

        ProxyInterceptor.getCurrentInstance().setTestClass(testClass);
        ArchiveManager.getCurrentInstance().initializeTestSuiteArchive();
        WebappTesterImpl.getCurrentInstance().initializeWebappTester();
        
        injectWebappTester();
    }

    public void injectAssertableProxies(Object testObj) {
        List<Field> assertFieldList = AnnotationManager.getCurrentInstance().getAssertFieldList();

        for (Field f : assertFieldList) {

            try {
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }

                if (f.get(testObj) == null) {
                    Object newFieldProxy = createProxy(f.getType());
                    f.set(testObj, newFieldProxy);
                }
            } catch (IllegalAccessException e) {
                log.log(Level.SEVERE, "Could not access field: " + f, e);
            }
        }
    }

    public void atServletConfiguration() {
        final Application application = ((ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY)).getApplication();

        ((ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY)).setApplication(new ApplicationWrapper() {

            private ELResolverWrapper wrappedELR = new ELResolverWrapper(application);
            private ActionListenerWrapper wrappedAL = new ActionListenerWrapper(application);

            @Override
            public ActionListener getActionListener() {
                return wrappedAL;
            }

            @Override
            public ELResolver getELResolver() {
                return wrappedELR;
            }

            @Override
            public Application getWrapped() {
                return application;
            }
        });
    }

    public boolean isTestSuiteConfig() {
        return ArchiveManager.getCurrentInstance().isTestSuiteConfig();
    }
    
    private void configureResources() {

        // add Impl dependent resources
        ResourceFinder.setResource(ARCHIVE_MANAGER, new ArchiveManager());
        ResourceFinder.setResource(ANNOTATION_MANAGER, new AnnotationManager());
        ResourceFinder.setResource(PROXY_INTERCEPTOR, new ProxyInterceptor());
        ResourceFinder.setResource(TEST_ASSERT_ERRORS, new TesttErrorManager());

        // add API dependent resources
        ResourceFinder.setResource(ResourceFinder.WEBAPP_TESTER, createProxy(DEFAULT_WEBAPP_TESTER ));

    }
                                                          
    private Object createProxy(Class pClass) {
        ProxyInterceptor proxyInterceptor = ProxyInterceptor.getCurrentInstance();

        return proxyInterceptor.newInstance(pClass);
    }


    private void injectWebappTester() {
        Field testerField = AnnotationManager.getCurrentInstance().getTesterField();
                                    
        try {
            if (!testerField.isAccessible())
                testerField.setAccessible(true);

            testerField.set(null, WebappTesterImpl.getCurrentInstance());
        } catch (IllegalAccessException e) {
            log.log(Level.SEVERE, "Could not access tester field: " + testerField, e);
        }
    }

}
